package com.wyz.saas.app.mvvm.launch

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.saop.annotation.AopIntercept
import com.wyz.saas.app.Account
import com.wyz.saas.app.R
import com.wyz.saas.app.databinding.ActivityLaunchBinding
import com.wyz.saas.app.mvvm.AppViewModelFactory
import com.wyz.saas.app.mvvm.account.AccountActivity
import com.wyz.saas.common.base.AbstractApiActivity
import net.qiujuer.genius.ui.widget.Loading


class LaunchActivity : AbstractApiActivity<ActivityLaunchBinding, LaunchViewModel>() {

    companion object {
        @AopIntercept(Account.SAOP_IS_LOGIN)
        fun skipMain(context: Context): Boolean {
            return true
        }
    }

    override fun initContentView(savedInstanceState: Bundle?): Int = R.layout.activity_launch

    override fun initViewModel(): LaunchViewModel = ViewModelProvider(this, AppViewModelFactory).get(LaunchViewModel::class.java)

    override fun initData(view: View?) {
        super.initData(view)
        view?.also {
            findViewById<Loading>(R.id.loading).start()
            window.decorView.postDelayed({ waitPushReceiverId() }, 500)
        }
    }

    /**
     * 等待个推框架对我们的PushId设置好值
     */
    private fun waitPushReceiverId() {
        if (Account.isLogin()) {
            // 已经登录情况下，判断是否绑定
            // 如果没有绑定则等待广播接收器进行绑定
            if (Account.isBind()) {
                skip()
                return
            }
        } else {
            // 没有登录
            // 如果拿到了PushId, 没有登录是不能绑定PushId的
            if (!TextUtils.isEmpty(Account.getPushId())) {
                // 跳转
                skip()
                return
            }
        }
        // 循环等待
        window.decorView.postDelayed({ waitPushReceiverId() }, 500)
    }

    private fun skip() {
        try {
            findViewById<Loading>(R.id.loading).stop()
            // 检查跳转到主页还是登录
            if (!skipMain(this)) {
                AccountActivity.show(this)
            }
        } finally {
            finish()
        }
    }
}